
// node 核心模块 http 和 https 不仅可以构建服务器，也可以发送请求
const https = require("https")

const Router = require("koa-router");
const router = new Router();

router.get("/", async function (ctx) {
    ctx.body = "welcome";
});


let httpsRequest = function (url) {
    return new Promise(function (resolve, reject) {
        https.get(url, function (res) {
            res.on('data', (d) => {
                resolve(d);
            });
        })
        .on('error', (e) => {
            reject(e);
        });
    })
}
router.post("/getOpenid", async function (ctx) {
    try {
        let appid = "你自己的appid";
        let appSecret = "你自己的appSecret";
        let code = ctx.request.body.code;
    
        // // 向微信的授权服务器再次发生请求
        let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`
        let result = await httpsRequest(url)
        //  在服务器端直接存储到本地数据库进行保存
        ctx.body = result;
        
    } catch (error) {
        ctx.body = error
    }


});

exports.router = router;